﻿Imports Business
Imports DTO

Public Class frmMonthly


    Dim bsOrganization As BSOrganization

    Dim bsMonthly As BSMonthly

    Dim scolStartMonth As String = "Start Month"
    Dim scolCutOff As String = "Cut Off Date"
    Dim scolUnit As String = "Unit Minutes"

    Dim dtMonthly As DataTable

    Dim listDtoMonthly As ArrayList

    Dim strErr1 As String = "Start month value is not valid."
    Dim strErr2 As String = "Cut off date >= 1 or <= 31."
    Dim strErr3 As String = "Cut off date cannot empty."
    Dim strErr4 As String = "Unit minutes cannot empty."
    Dim strErr5 As String = "Start month is duplicated."
    Dim strErr6 As String = "Update error"
    Dim strMsg1 As String = "Update successful."

    Dim yearFrom As Integer = 2000

    Dim yearTo As Integer = 2020

    Dim serverName As String

    Public Sub New(ByVal serverName As String)

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Me.serverName = serverName

        bsOrganization = New BSOrganization(Me.serverName)

        bsMonthly = New BSMonthly(Me.serverName)

        listDtoMonthly = New ArrayList

        ' Template column
        Dim cell As DataGridViewCell = New DataGridViewTextBoxCell()

        ' add column start month    
        Dim colStartMotnh As DataGridViewColumn = New DataGridViewColumn
        colStartMotnh.HeaderText = scolStartMonth
        colStartMotnh.Name = scolStartMonth
        colStartMotnh.CellTemplate = cell
        grdMonthly.Columns.Add(colStartMotnh)

        ' add column Cut off date    
        Dim colCutOffDate As DataGridViewColumn = New DataGridViewColumn
        colCutOffDate.HeaderText = scolCutOff
        colCutOffDate.Name = scolCutOff
        colCutOffDate.CellTemplate = cell
        grdMonthly.Columns.Add(colCutOffDate)

        ' add column unit minute   
        Dim colUnit As DataGridViewComboBoxColumn = New DataGridViewComboBoxColumn()
        colUnit.HeaderText = scolUnit
        colUnit.Name = scolUnit
        colUnit.DisplayStyle = ComboBoxStyle.DropDownList
        colUnit.Items.Add("1")
        colUnit.Items.Add("5")
        colUnit.Items.Add("10")
        colUnit.Items.Add("15")
        colUnit.Items.Add("30")
        colUnit.Items.Add("60")
        grdMonthly.Columns.Add(colUnit)



    End Sub



    Private Sub frmMonthly_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ' fill combobox organizations are company
        Functions.FillComboBox(cboCom, bsOrganization.GetCompany())

        'select first element 
        cboCom.SelectedIndex = 1
        
       

    End Sub

    ''' <summary>
    ''' Load data grid view monthly
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub LoadGrdMonthly()

        'clear datagridview
        grdMonthly.Rows.Clear()

        dtMonthly = bsMonthly.GetMonthly(cboCom.SelectedValue)

        If Not dtMonthly Is Nothing Then

            Dim gridViewRow As DataGridViewRow

            For Each row As DataRow In dtMonthly.Rows

             


                gridViewRow = New DataGridViewRow

                Dim cell As DataGridViewCell = New DataGridViewTextBoxCell()

                ' cell start month
                If Not row.Item("EXPIRATION_FROM").ToString().Equals("0") Then

                    cell.Value = Functions.ConvertStrDBMonthToStrMonth(row.Item("EXPIRATION_FROM"))
                    
                Else

                    cell.Value = ""

                End If

                gridViewRow.Cells.Add(cell)


                ' cell cut off date
                cell = New DataGridViewTextBoxCell()

                cell.Value = row.Item("CUT_OFF_DATE")
                gridViewRow.Cells.Add(cell)

                ' cell unit minutes
                Dim cboCell As DataGridViewComboBoxCell = New DataGridViewComboBoxCell()

                cboCell.DisplayStyle = ComboBoxStyle.DropDownList
                cboCell.Items.Add("1")
                cboCell.Items.Add("5")
                cboCell.Items.Add("10")
                cboCell.Items.Add("15")
                cboCell.Items.Add("30")
                cboCell.Items.Add("60")
                For Each item As Object In cboCell.Items

                    If item.ToString().Equals(row.Item("UNIT_MINUTES").ToString()) Then

                        cboCell.Value = item

                        Exit For

                    End If

                Next

                gridViewRow.Cells.Add(cboCell)
                

                grdMonthly.Rows.Add(gridViewRow)

            Next


        End If

    End Sub


    Private Sub cboCom_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCom.SelectedIndexChanged

        If cboCom.SelectedIndex > 0 Then

            LoadGrdMonthly()

        Else

            grdMonthly.Rows.Clear()
            
        End If


    End Sub

    Private Sub grdMonthly_CellBeginEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles grdMonthly.CellBeginEdit

        ' column start month
        If e.ColumnIndex = 0 Then

            If Not String.IsNullOrEmpty(grdMonthly.Rows.Item(e.RowIndex).Cells.Item(0).Value) Then

                ' convert string MM/yyyy to integer
                grdMonthly.Rows.Item(e.RowIndex).Cells.Item(0).Value = Functions.ConvertStrMonthToInt(grdMonthly.Rows.Item(e.RowIndex).Cells.Item(0).Value.ToString())
                
            End If

        End If

    End Sub



    Private Sub grdMonthly_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdMonthly.CellEndEdit

        If e.ColumnIndex = 0 Then

            ' column start month
            If Not String.IsNullOrEmpty(grdMonthly.Rows.Item(e.RowIndex).Cells.Item(0).Value) Then

                'validate string month
                If Functions.ValidateStrMonth(Integer.Parse(grdMonthly.Rows.Item(e.RowIndex).Cells.Item(0).Value).ToString("##/####"), yearFrom, yearTo) Then

                    If Not CheckMonthlyExisted(Integer.Parse(grdMonthly.Rows.Item(e.RowIndex).Cells.Item(0).Value).ToString("##/####"), e.RowIndex) Then

                        'convert to str MM/yyyy
                        grdMonthly.Rows.Item(e.RowIndex).Cells.Item(0).Value = Integer.Parse(grdMonthly.Rows.Item(e.RowIndex).Cells.Item(0).Value).ToString("0#/####")

                        ' clear message
                        lblMessage.Text = Nothing

                    Else

                        ' print error message start month is duplicated
                        lblMessage.Text = strErr5

                        ' clear wrong value
                        grdMonthly.Rows.Item(e.RowIndex).Cells.Item(0).Value = Nothing

                    End If


                Else

                    ' print error message start month is not valid
                    lblMessage.Text = strErr1

                    'clear wrong value
                    grdMonthly.Rows.Item(e.RowIndex).Cells.Item(0).Value = Nothing

                End If

                ' start month = null check duplicated
            Else

                If Not CheckMonthlyExisted(Nothing, e.RowIndex) Then

                    lblMessage.Text = Nothing

                Else

                    ' print error message start month is duplicated
                    lblMessage.Text = strErr5


                    'clear value
                    grdMonthly.Rows.Item(e.RowIndex).Cells.Item(1).Value = Nothing

                End If

            End If

        ElseIf e.ColumnIndex = 1 Then

            If Not String.IsNullOrEmpty(grdMonthly.Rows.Item(e.RowIndex).Cells.Item(1).Value) Then

                Dim cutOffDate As Integer = Integer.Parse(grdMonthly.Rows.Item(e.RowIndex).Cells.Item(1).Value)

                If cutOffDate > 0 And cutOffDate < 32 Then

                    If Not CheckMonthlyExisted(grdMonthly.Rows.Item(e.RowIndex).Cells.Item(0).Value, e.RowIndex) Then

                        ' clear message
                        lblMessage.Text = Nothing

                    Else

                        ' print error message start month is duplicated
                        lblMessage.Text = strErr5

                        'clear value
                        grdMonthly.Rows.Item(e.RowIndex).Cells.Item(1).Value = Nothing

                    End If


                Else

                    ' print message error 31 >= cut off date >= 1 
                    lblMessage.Text = strErr2

                    ' clear wrong value
                    grdMonthly.Rows.Item(e.RowIndex).Cells.Item(1).Value = Nothing


                End If

            End If

        End If

    End Sub


    Private Sub grdMonthly_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles grdMonthly.EditingControlShowing

        Dim control As Control = e.Control

        If grdMonthly.CurrentCell.ColumnIndex <> 2 Then

            RemoveHandler control.KeyPress, AddressOf Handle_KeyPress
            AddHandler control.KeyPress, AddressOf Handle_KeyPress

        Else

            RemoveHandler control.KeyPress, AddressOf Handle_KeyPress

        End If

    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Handle_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)


        Dim txtCell As TextBox = sender

        'column start month
        If grdMonthly.CurrentCell.ColumnIndex = 0 Then

            ' set text length max is 6
            txtCell.MaxLength = 6

            ' column cut off date
        Else

            txtCell.MaxLength = 2

        End If

        ' check allow only number and control
        If (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then

            e.Handled = False

        Else

            e.Handled = True

        End If




    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click

        ' validate gridview monthly
        If ValidateMonthly() Then

            Dim dtoMonthly As DTOMonthly

            For i As Integer = 0 To grdMonthly.Rows.Count - 2

                ' check row not empty
                If Not grdMonthly.Rows.Item(i).Cells.Item(1).Value Is Nothing Then


                    'lblMessage.Text = grdMonthly.Rows.Item(i).Cells.Item(0).Value.ToString() & " --- " & grdMonthly.Rows.Item(i).Cells.Item(2).Value.ToString()

                    dtoMonthly = New DTOMonthly()

                    ' organization no
                    dtoMonthly.OrganNoProperty = cboCom.SelectedValue

                    ' ex from no
                    If grdMonthly.Rows.Item(i).Cells.Item(0).Value Is Nothing Then

                        dtoMonthly.ExFromProperty = "0"

                    ElseIf String.IsNullOrEmpty(grdMonthly.Rows.Item(i).Cells.Item(0).Value.ToString()) Then

                        dtoMonthly.ExFromProperty = "0"

                    Else
                        
                        dtoMonthly.ExFromProperty = Functions.ConvertStrMonthToStrDBMonth(grdMonthly.Rows.Item(i).Cells.Item(0).Value.ToString())

                    End If

                    ' cut off date
                    dtoMonthly.CutOffProperty = grdMonthly.Rows.Item(i).Cells.Item(1).Value.ToString()

                    ' unit minutes
                    dtoMonthly.UnitMinuteProperty = grdMonthly.Rows.Item(i).Cells.Item(2).Value.ToString()

                    ' create time
                    If i < dtMonthly.Rows.Count Then

                        dtoMonthly.CreateDateProperty = dtMonthly.Rows.Item(i).Item("CREATE_DATE_TIME")

                    Else

                        dtoMonthly.CreateDateProperty = Date.Now

                    End If

                    ' update time
                    dtoMonthly.UpdateDateProperty = Date.Now

                    listDtoMonthly.Add(dtoMonthly)


                End If
                
            Next

            ' sort start date of monthlys into increase order 
            bsMonthly.SortMonthly(listDtoMonthly)

            ' set end month (expiration from)
            For j As Integer = 0 To listDtoMonthly.Count - 2

                Dim r As Integer = Integer.Parse(DirectCast(listDtoMonthly.Item(j + 1), DTOMonthly).ExFromProperty) - Integer.Parse(DirectCast(listDtoMonthly.Item(j), DTOMonthly).ExFromProperty)

                ' start month of j + 1 monthly is greater than monthly j, >1 month.
                If r > 1 Then

                    ' end month of monthly j = start month of monthly j + 1 subtract 1.
                    DirectCast(listDtoMonthly.Item(j), DTOMonthly).ExToProperty = bsMonthly.SubtractMonth(Integer.Parse(DirectCast(listDtoMonthly.Item(j + 1), DTOMonthly).ExFromProperty))

                    ' start month of j + 1 monthly is greater than monthly j 1 month.
                Else

                    DirectCast(listDtoMonthly.Item(j), DTOMonthly).ExToProperty = DirectCast(listDtoMonthly.Item(j), DTOMonthly).ExFromProperty

                End If

            Next

            'set ex from for monthly lastest
            DirectCast(listDtoMonthly.Item(listDtoMonthly.Count - 1), DTOMonthly).ExToProperty = "999999"

            ' update to database
            ' First, delete all monthly of organization current in database
            bsMonthly.DeleteAllMonthly(cboCom.SelectedValue)

            Dim flag As Boolean
            ' insert list monthly to database
            For Each monthly As DTOMonthly In listDtoMonthly

                If Not bsMonthly.AddMonthly(monthly) Then

                    flag = True

                End If

            Next

            If flag Then

                'print error message update error
                lblMessage.Text = strErr6

            Else

                'print message update successful
                lblMessage.Text = strMsg1


            End If

        End If

    End Sub


    ''' <summary>
    ''' Check monthly if it is existed in datagridview
    ''' </summary>
    ''' <param name="startMonth"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckMonthlyExisted(ByVal startMonth As Object, ByVal index As Integer) As Boolean

        Dim month As String

        If startMonth Is Nothing Then

            month = ""

        Else

            month = startMonth.ToString()

        End If

        For i As Integer = 0 To grdMonthly.Rows.Count - 2

            If i <> index And Not grdMonthly.Rows.Item(i).Cells.Item(0).Value Is Nothing Then

                ' if it is existed
                If grdMonthly.Rows.Item(i).Cells.Item(0).Value.ToString().Equals(month) Then

                    Return True

                End If

            End If
            
        Next

        Return False

    End Function

   

    ''' <summary>
    ''' validate input monthly
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Function ValidateMonthly() As Boolean

        For i As Integer = 0 To grdMonthly.Rows.Count - 2

            If Not grdMonthly.Rows.Item(i).Cells.Item(0).Value Is Nothing Then

                If Not grdMonthly.Rows.Item(i).Cells.Item(1).Value Is Nothing Then

                    If Not grdMonthly.Rows.Item(i).Cells.Item(2).Value Is Nothing Then

                        ' clear message
                        lblMessage.Text = Nothing

                    Else

                        ' print error message unit minutes not null
                        lblMessage.Text = strErr4

                        Return False

                    End If

                Else

                    ' print error message cut off date not null 
                    lblMessage.Text = strErr3

                    Return False
                    
                End If

            Else

                If Not grdMonthly.Rows.Item(i).Cells.Item(1).Value Is Nothing Then

                    If Not grdMonthly.Rows.Item(i).Cells.Item(2).Value Is Nothing Then

                        ' clear message
                        lblMessage.Text = Nothing

                    Else

                        ' print error message unit minutes not null
                        lblMessage.Text = strErr4

                        Return False

                    End If

                ElseIf Not grdMonthly.Rows.Item(i).Cells.Item(2).Value Is Nothing Then

                    ' print error message cut off date not null 
                    lblMessage.Text = strErr3

                    Return False

                Else

                    ' two cells are null it is true
                    ' clear message
                    lblMessage.Text = Nothing

                End If

            End If
            
        Next

        Return True

    End Function

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click

        frmMain.RemoveTabpage()

    End Sub
End Class